'use strict';

const Service = require('egg').Service;
const sequelize = require('sequelize')
const { Op } = require('sequelize').Sequelize;
const format = require('dateformat');

class LendService extends Service {

    async add(request) {
        const { LendedInfo, Book, User } = this.ctx.model;

        let book = await Book.findOne({
            where: {
                id: request.bookId
            }
        });

        if (!book) {
            this.ctx.throw(400, "书籍ID错误，请确认后再试！");
        }

        if (!book.onSale) {
            this.ctx.throw(400, "当前书籍未上架！");
        }

        if (book.lended) {
            this.ctx.throw(400, "当前书籍已被借出！");
        }

        let user = await User.findOne({
            where: {
                id: request.userId,
                role: 'customer'
            }
        });

        if (!user) {
            this.ctx.throw(400, "用户ID错误，请确认后再试！");
        }

        let now = new Date();
        let info = {
            createDate: now,
            createBy: this.ctx.state.user.id
        }
        info.userId = request.userId;
        info.bookId = request.bookId;
        info.lendedDate = now;
        info.returnDate = new Date(now.getTime() + request.day * 24 * 60 * 60 * 1000);
        info.broken = 0;
        info.pay = 0;

        const retBook = await LendedInfo.create(info);

        book.lended = 1;
        book.updateDate = new Date();
        book.updateBy = this.ctx.state.user.id;
        await book.save()

        return {
            result: true
        }
    }

    async list(pageNo, pageSize, filter) {
        const offset = pageSize * (pageNo - 1);
        const limit = pageSize;

        const { idCard, userId, bookId } = filter;

        let sql = 'SELECT b.id, b.user_id userId, b.book_id bookId, t.name name, u.nick_name nickName, '
        sql += 'b.lended_date lendedDate, b.return_date returnDate, b.actual_return_date actualReturnDate, b.broken, t.on_sale onSale, t.lended, b.create_date createDate FROM lended_info b '
        sql += 'join book t on b.book_id = t.id join user u on u.id = b.user_id where';
        if (idCard) sql += ` u.id_card like '%${idCard}%'`;
        if (userId) sql += ` u.id = ${userId}`;
        if (bookId) sql += ` t.id = ${bookId}`;
        if (!idCard && !userId && !bookId) sql = sql.replace('where', '')
        sql+=" order by b.create_date desc"
        const infos = await this.ctx.model.query(sql, { type: sequelize.QueryTypes.SELECT });

        let hasNextPage = pageNo * pageSize < infos.length;

        let result = {
            totalCount: infos.length,
            pageNo,
            pageSize,
            infos: infos.splice(offset, limit),
            hasNextPage,
        };

        return result;
    }

    async update(request) {
        const { LendedInfo } = this.ctx.model;
        let info = await LendedInfo.findOne({
            where: {
                id: request.id
            }
        });

        if (!info) {
            this.ctx.throw(404, '书籍不存在！')
        }

        info.returnDate = new Date(info.returnDate.getTime() + request.day * 24 * 60 * 60 * 1000);
        info.updateDate = new Date();
        info.updateBy = this.ctx.state.user.id;
        await info.save();

        return {
            result: true
        };

    }

    async calculate() {
        const { id, broken } = this.ctx.query;
        const { LendedInfo, Book } = this.ctx.model;
        let info = await LendedInfo.findOne({
            where: {
                id: id
            }
        });

        if (!info) {
            this.ctx.throw(404, '信息已过期！')
        }

        const book = await Book.findOne({
            where: {
                id: info.bookId
            }
        });

        const { Library } = this.ctx.model;
        let library = await Library.findOne({
            where: {
                id: 1
            }
        });

        if (!library) {
            this.ctx.throw(404, '配置不存在！')
        }
        let diff = new Date().getTime() - info.lendedDate.getTime();   //时间差的毫秒数    

        let days = Math.floor(diff / (24 * 3600 * 1000))
        let fine = 0;
        if (broken == '1') fine = Number.parseFloat(book.price);
        let perDayPay = Number.parseFloat(library.perDayPay);
        info.pay = days * perDayPay + fine;
        info.broken = broken;
        info.updateDate = new Date();
        info.updateBy = this.ctx.state.user.id;
        await info.save();

        return {
            pay: info.pay
        };
    }

    async return(request) {
        const { LendedInfo, Book } = this.ctx.model;
        let info = await LendedInfo.findOne({
            where: {
                id: request.id
            }
        });

        if (!info) {
            this.ctx.throw(404, '信息已过期！')
        }

        info.pay = request.pay ? request.pay : info.pay;
        info.broken = request.broken ? request.broken : info.broken;
        info.actualReturnDate = new Date();
        info.updateDate = new Date();
        info.updateBy = this.ctx.state.user.id;
        await info.save();

        const book = await Book.findOne({
            where: {
                id: info.bookId
            }
        });
        if (book) {
            book.lended = 0;
            book.updateDate = new Date();
            book.updateBy = this.ctx.state.user.id;
            await book.save();
        }
        return {
            result: true
        };
    }
}
module.exports = LendService;
